<template>
	<view class="container">
		<!-- 时间范围选择器 -->
		<view class="date-selector">
			<text class="date-label">统计区间</text>
			<uni-datetime-picker
				type="daterange"
				v-model="dateRange"
				:start="minDate"
				:end="maxDate"
				@change="onDateRangeChange"
				rangeSeparator="至"
				:clear-icon="false"
			/>
		</view>
		
		<!-- 收支总览 -->
		<view class="overview-card">
			<view class="overview-item">
				<text class="label">总收入</text>
				<text class="amount income">¥{{totalIncome}}</text>
			</view>
			<view class="overview-item">
				<text class="label">总支出</text>
				<text class="amount expense">¥{{totalExpense}}</text>
			</view>
			<view class="overview-item">
				<text class="label">结余</text>
				<text class="amount balance">¥{{balance}}</text>
			</view>
		</view>
		
		<!-- 收支趋势图 -->
		<view class="chart-card">
			<view class="card-title">收支趋势</view>
			<view class="chart-container">
				<qiun-data-charts 
					type="line"
					:opts="lineOpts"
					:chartData="lineData"
				/>
			</view>
		</view>
		
		<!-- 分类统计 -->
		<view class="chart-card">
			<view class="card-title">支出分类</view>
			<view class="chart-container">
				<qiun-data-charts 
					type="pie"
					:opts="pieOpts"
					:chartData="pieData"
				/>
			</view>
			<view class="category-list">
				<view v-for="(category, index) in expenseCategories" :key="index" class="category-item">
					<view class="category-info">
						<view class="category-color" :style="{backgroundColor: category.color}"></view>
						<text class="category-name">{{category.name}}</text>
					</view>
					<view class="category-amount">
						<text class="amount">¥{{category.amount}}</text>
						<text class="percentage">({{category.percentage}}%)</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		const today = new Date();
		const ym = today.toISOString().slice(0,7);
		const firstDay = ym + '-01';
		const lastDay = today.toISOString().slice(0,10);
		return {
			dateRange: [firstDay, lastDay],
			minDate: '2000-01-01',
			maxDate: lastDay,
			totalIncome: 0,
			totalExpense: 0,
			balance: 0,
			expenseCategories: [],
			// 折线图配置
			lineOpts: {
				color: ['#4cd964', '#ff3b30'],
				padding: [15, 15, 0, 15],
				legend: {
					show: true,
					position: 'top',
					float: 'right',
					padding: 20,
					margin: 0,
					textAlign: 'center',
					textBaseline: 'middle'
				},
				xAxis: {
					disableGrid: false,
					gridType: 'dash',
					dashLength: 2,
					itemCount: 5,
					textAlign: 'center',
					textBaseline: 'middle'
				},
				yAxis: {
					gridType: 'dash',
					dashLength: 2,
					data: [{ min: 0 }],
					textAlign: 'right',
					textBaseline: 'middle'
				},
				extra: {
					line: {
						type: 'straight',
						width: 2
					}
				}
			},
			lineData: {
				categories: [],
				series: []
			},
			// 饼图配置
			pieOpts: {
				padding: [5, 5, 5, 5],
				legend: { show: false },
				extra: {
					pie: {
						activeRadius: 10,
						offsetAngle: 0,
						labelWidth: 15,
						border: true,
						borderWidth: 3,
						borderColor: '#FFFFFF'
					}
				},
				xAxis: { textAlign: 'center', textBaseline: 'middle' },
				yAxis: { textAlign: 'right', textBaseline: 'middle' }
			},
			pieData: { series: [] }
		}
	},
	onShow() {
		this.loadStatistics()
	},
	methods: {
		onDateRangeChange(e) {
			this.dateRange = e
			this.loadStatistics()
		},
		loadStatistics() {
			const records = uni.getStorageSync('records') || []
			const expenseCategories = uni.getStorageSync('expenseCategories') || []
			const incomeCategories = uni.getStorageSync('incomeCategories') || []
			// 过滤区间
			let [start, end] = this.dateRange
			if (!start || !end) {
				this.totalIncome = 0
				this.totalExpense = 0
				this.balance = 0
				this.lineData = { categories: [], series: [] }
				this.expenseCategories = []
				this.pieData.series = []
				return
			}
			const startDate = new Date(start)
			const endDate = new Date(end)
			const filtered = records.filter(r => {
				if (!r.date) return false
				const d = new Date(r.date)
				return d >= startDate && d <= endDate
			})

			// 统计总收入/支出
			let totalIncome = 0, totalExpense = 0
			filtered.forEach(r => {
				if (r.amount > 0) totalIncome += r.amount
				else totalExpense += Math.abs(r.amount)
			})
			this.totalIncome = totalIncome
			this.totalExpense = totalExpense
			this.balance = totalIncome - totalExpense

			// 收支趋势图（按天）
			const dateMap = {}
			filtered.forEach(r => {
				if (!r.date) return
				if (!dateMap[r.date]) dateMap[r.date] = { income: 0, expense: 0 }
				if (r.amount > 0) dateMap[r.date].income += r.amount
				else dateMap[r.date].expense += Math.abs(r.amount)
			})
			const dates = Object.keys(dateMap).sort()
			this.lineData = {
				categories: dates,
				series: [
					{ name: '收入', data: dates.map(d => dateMap[d].income) },
					{ name: '支出', data: dates.map(d => dateMap[d].expense) }
				]
			}

			// 分类统计（支出）
			const categoryMap = {}
			let total = 0
			filtered.forEach(r => {
				if (r.amount < 0) {
					categoryMap[r.type] = (categoryMap[r.type] || 0) + Math.abs(r.amount)
					total += Math.abs(r.amount)
				}
			})
			const categories = Object.keys(categoryMap)
			this.expenseCategories = categories.map(name => {
				const cat = expenseCategories.find(c => c.name === name) || {}
				return {
					name,
					amount: categoryMap[name],
					percentage: total ? Math.round(categoryMap[name] / total * 100) : 0,
					color: cat.color || '#007aff'
				}
			})
			this.pieData.series = [
				{
					data: this.expenseCategories.map(item => ({
						name: item.name,
						value: item.amount,
						color: item.color
					}))
				}
			]
		}
	}
}
</script>

<style>
.container {
	padding: 20rpx;
	padding-bottom: calc(140rpx + env(safe-area-inset-bottom));
}

.date-selector {
	background-color: #ffffff;
	border-radius: 20rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.date-label {
	font-size: 28rpx;
	color: #666;
	margin-bottom: 20rpx;
	display: block;
}

.uni-datetime-picker {
	width: 100%;
	margin-top: 10rpx;
}

.overview-card {
	background-color: #ffffff;
	border-radius: 20rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	display: flex;
	justify-content: space-between;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.overview-item {
	display: flex;
	flex-direction: column;
	align-items: center;
}

.label {
	font-size: 28rpx;
	color: #666;
	margin-bottom: 10rpx;
}

.amount {
	font-size: 36rpx;
	font-weight: bold;
}

.income {
	color: #4cd964;
}

.expense {
	color: #ff3b30;
}

.balance {
	color: #007aff;
}

.chart-card {
	background-color: #ffffff;
	border-radius: 20rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.card-title {
	font-size: 32rpx;
	font-weight: bold;
	margin-bottom: 20rpx;
}

.chart-container {
	height: 400rpx;
	margin-bottom: 30rpx;
}

.category-list {
	margin-top: 20rpx;
}

.category-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #eee;
}

.category-item:last-child {
	border-bottom: none;
}

.category-info {
	display: flex;
	align-items: center;
}

.category-color {
	width: 20rpx;
	height: 20rpx;
	border-radius: 50%;
	margin-right: 10rpx;
}

.category-name {
	font-size: 28rpx;
	color: #333;
}

.category-amount {
	display: flex;
	align-items: center;
}

.category-amount .amount {
	font-size: 28rpx;
	color: #333;
	margin-right: 10rpx;
}

.category-amount .percentage {
	font-size: 24rpx;
	color: #999;
}
</style> 